<template>
  <el-dialog
    title="表单设计"
    fullscreen
    :visible="visible"
    :append-to-body="true"
    :show-close="false"
    @close="handleDialogClose"
  >
    <fm-making-form
      class="form-making"
      ref="formMaking"
      preview
      generate-code
      generate-json
      clearable
    >
      <template slot="action">
        <el-button
          type="text"
          size="medium"
          icon="el-icon-document-checked"
          @click="handleFormDesignSave"
        >保存</el-button>
        <el-button
          class="close"
          type="text"
          size="medium"
          icon="el-icon-close"
          @click="handleDialogClose"
        >关闭</el-button>
      </template>
    </fm-making-form>
  </el-dialog>
</template>

<script>
import FormDesignService from '../../../../service/form_design'

export default {
  props: {
    show: {
      type: Boolean,
      required: true,
      default: () => false
    },
    data: {
      type: Object,
      required: true,
      default: () => {}
    }
  },
  data() {
    return {
      visible: false
    }
  },
  methods: {
    // 处理Dialog关闭事件
    handleDialogClose() {
      this.$emit('update:show')
    },
    // 处理表单设计保存
    handleFormDesignSave() {
      const json = this.$refs.formMaking.getJSON()
      let form = JSON.parse(JSON.stringify(this.data))
      form.content = JSON.stringify(json)

      FormDesignService.updateForm(form).then(res => {
        this.$message.success('保存成功')
        this.$emit('success')
        this.handleDialogClose()
      })
    }
  },
  watch: {
    show(value) {
      if (value) {
        this.$nextTick(() => {
          const content = this.data.content
          if (content) {
            const json = JSON.parse(content)
            this.$refs.formMaking.setJSON(json)
          } else {
            this.$refs.formMaking.handleClear()
          }
        })
      }
      this.visible = value
    }
  }
}
</script>

<style lang="stylus" scoped>
>>> .el-dialog__body
  padding 0
.form-making
  height calc(100vh - 55px)
  .close
    color red
</style>
